package common.files.xml.xsd;

import java.util.Iterator;

import common.utils.StringHelper;

public class ElementXsd extends NodeXsd{
	
	protected String value;
	
	public ElementXsd(){
		super();
	}
	
	public ElementXsd(String name){
		super(name);
	}

	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
	@Override
	public String toString(){
		if(StringHelper.isEmpty(this.name)){
			return "";
		}
		StringBuffer sb_result = new StringBuffer();
		sb_result.append("<" + this.name + ">");
		if(!this.children.isEmpty()){
			Iterator<ElementXsd> ite = this.children.iterator();
			while(ite.hasNext()){
				sb_result.append(ite.next().toString());
			}
		}
		sb_result.append("</" + this.name + ">");
		
		return sb_result.toString();
	}
	
	public boolean eaquals(ElementXsd target){
		boolean eaquals = true;
		if (!this.name.equalsIgnoreCase(target.getName())) {
			return eaquals = false;
		}
		if (!this.children.isEmpty()) {
			Iterator<ElementXsd> ite = this.children.iterator();
			ElementXsd child;
			while(ite.hasNext()){
				child = ite.next();
				if(child != null && !child.eaquals(target)){
					return eaquals = false;
				}
			}
		}

		return eaquals;
	}
	
	public boolean exists(ElementXsd target){
		boolean exists = false;
		if (this.name.equalsIgnoreCase(target.getName())) {
			return exists = true;
		}
		return exists;
	}
	
	public void updateElememtXsd(ElementXsd target){
		if(target.children.isEmpty()){
			return;
		}
		if(this.children.isEmpty()){
			this.setChildren(target.getChildren());
			return;
		}
		Iterator<ElementXsd> tar_ite = target.children.iterator();
		ElementXsd tar_child;
		Iterator<ElementXsd> cur_ite;
		ElementXsd cur_child;
		while(tar_ite.hasNext()){
			tar_child = tar_ite.next();
			cur_ite = this.children.iterator();
			boolean existsInChildren = false;
			while(cur_ite.hasNext()){
				cur_child = cur_ite.next();
				if(tar_child.getName().equalsIgnoreCase(cur_child.getName())){
					existsInChildren = true;
					cur_child.updateElememtXsd(tar_child);
					break;
				}
			}
			if(!existsInChildren){
				this.addChild(tar_child);
			}
		}
	}
	
	
	
	
}
